package com.woyou.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.EBean;

import com.woyou.Constant;
import com.woyou.utils.FileUtils;

import android.text.TextUtils;
import android.util.Log;

/**
 * 文件业务逻辑控制器
 * 
 * @author longtao.li
 *
 */
@EBean
public class FileModel extends SuperModel {

	@AfterInject
	@Override
	protected void onInit() {

	}

	/**
	 * 读取ServerConfig配置文件的内容
	 */
	public void loadConfig() {

		String filePath = FileUtils.getConfigFilePath();
		if (filePath == null) {
			return;
		}

		InputStream in = null;
		try {

			File file = new File(filePath);
			if (file.exists()) {
				in = getConfigfile();
			}

		} catch (Exception e) {
			Log.e("LOADCONFIG", e.getMessage(), e);

		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 从sd卡的配置文件读取配置信息
	 * 
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public InputStream getConfigfile() throws FileNotFoundException, IOException {
		String filePath = FileUtils.getConfigFilePath();
		if (filePath == null)
			return null;
		Properties props = new Properties();
		InputStream in;
		in = new FileInputStream(filePath);
		props.load(in);

		String address = props.getProperty("SERVER_ADDRESS");
		Constant.SERVER_ADDRESS = TextUtils.isEmpty(address) ? Constant.SERVER_ADDRESS : address;

		String sjPort = props.getProperty("SJ_PORT");
		Constant.SJ_PORT = TextUtils.isEmpty(sjPort) ? "100" : sjPort;

		// web服务器
		String webAddress = props.getProperty("WEB_ADDRESS");
		Constant.WEB_ADDRESS = TextUtils.isEmpty(webAddress) ? Constant.WEB_ADDRESS : webAddress;
		
		String webPort = props.getProperty("WEB_PORT");
		Constant.WEB_PORT = TextUtils.isEmpty(webPort) ? "100" : webPort;

		return in;
	}
	

}
